<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="分数" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入分数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 号码MD5 -->
      <el-form-item label="MD5" prop="phoneMd5">
        <el-input
          v-model="queryParams.phoneMd5"
          placeholder="请输入号码MD5"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 业务标签（多选，PHONE_TAG 字典） -->
      <el-form-item label="业务标签" prop="phoneTags">
        <el-select
          v-model="queryParams.phoneTags"
          placeholder="请选择业务标签"
          multiple
          collapse-tags
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PHONE_TAG)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 名单等级（LIST_LEVEL 字典，字符串枚举） -->
      <el-form-item label="名单等级" prop="listLevel">
        <el-select
          v-model="queryParams.listLevel"
          placeholder="请选择名单等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.LIST_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 名单日期（yyyy-MM-dd，区间） -->
      <el-form-item label="名单日期" prop="listDate">
        <el-date-picker
          v-model="queryParams.listDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:marketing-score:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="号码" align="center" prop="phoneE164" />
      <el-table-column label="MD5" align="center" prop="phoneMd5" />
      <el-table-column label="分数" align="center" prop="score" />

      <!-- 业务标签（逗号分隔串 -> 标签渲染） -->
      <el-table-column label="业务标签" align="center" prop="phoneTags">
        <template #default="{ row }">
          <div class="flex flex-wrap gap-1 justify-center">
            <dict-tag
              v-for="v in splitTags(row.phoneTags)"
              :key="v"
              :type="DICT_TYPE.PHONE_TAG"
              :value="v"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 名单等级（LIST_LEVEL 字典） -->
      <el-table-column label="名单等级" align="center" prop="listLevel">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.LIST_LEVEL" :value="row.listLevel" />
        </template>
      </el-table-column>

      <!-- 名单日期 -->
      <el-table-column
        label="名单日期"
        align="center"
        prop="listDate"
        width="140px"
      />
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MarketingScoreForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { MarketingScoreApi } from '@/api/vos/marketingscore'
import MarketingScoreForm from './MarketingScoreForm.vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

/** 名单评分 列表 */
defineOptions({ name: 'MarketingScore' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<any[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  score: undefined as number | undefined,

  // 新增 / 调整的查询项
  listDate: [] as string[],              // yyyy-MM-dd 的起止日期数组
  phoneMd5: undefined as string | undefined,
  phoneTags: [] as string[],             // 多选
  listLevel: undefined as string | undefined // LIST_LEVEL：string 枚举
})

const queryFormRef = ref()
const exportLoading = ref(false)

/** 将逗号分隔的标签字符串拆成数组 */
const splitTags = (s?: string) => {
  if (!s) return []
  return s.split(',').map(v => v.trim()).filter(Boolean)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MarketingScoreApi.getMarketingScorePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.phoneTags = []   // 手动重置多选
  queryParams.listDate = []    // 手动重置日期区间
  handleQuery()
}

/** 表单 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 批量选择/删除 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: any[]) => {
  checkedIds.value = records.map((item) => item.id)
}
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await MarketingScoreApi.deleteMarketingScoreList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 单条删除 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await MarketingScoreApi.deleteMarketingScore(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await MarketingScoreApi.exportMarketingScore(queryParams)
    download.excel(data, '名单评分.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
